package processing.wimm.accelerometer;

//import java.lang.reflect.Method;

import java.lang.reflect.Method;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import processing.core.*;

public class AcceleroLib implements SensorEventListener{
	PApplet parent;
	Method acceleroEventMethod;
	private SensorManager mySensorManager;
	public float x,y,z;
	
	public AcceleroLib(PApplet tparent){
		parent = tparent;
		mySensorManager = (SensorManager)parent.getSystemService(Context.SENSOR_SERVICE);
		mySensorManager.registerListener(this, mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
		//parent.registerDispose(this);
		try {
			acceleroEventMethod = parent.getClass().getMethod("acceleroEvent", new Class[] { float.class, float.class, float.class });
		} catch (Exception e) {
			// ignore
		}

	}
	
	@Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        	if (acceleroEventMethod != null) {
        	    try {
        	    	x = event.values[0];
        	    	y = event.values[1];
        	    	z = event.values[2];
        	    	acceleroEventMethod.invoke(parent, new Object[] { x,y,z });
        	    } catch (Exception e) {
        	      System.err.println("Disabling acceleroEvent() because of an error.");
        	      e.printStackTrace();
        	      acceleroEventMethod = null;
        	    }
        	  }
        }
    }
	
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

}
